from google.appengine.api import mail

class GAEMailConnection(object):
    """
    A wrapper that manages the GAE Mail API.
    """

    def __init__(self, fail_silently=False):
        self.fail_silently = fail_silently

    def send_messages(self, email_messages):
        """
        Sends one or more EmailMessage objects and returns the number of email
        messages sent.
        """
        if not email_messages:
            return
        num_sent = 0
        for message in email_messages:
            sent = self._send(message)
            if sent:
                num_sent += 1
        return num_sent

    def _send(self, email_message):
        """A helper method that does the actual sending."""
        if not email_message.to:
            return False
        try:
            if email_message.attachments:
                msg = mail.send_mail(sender=email_message.from_email,
                                     to=email_message.recipients(),
                                     subject=email_message.subject,
                                     body=email_message.body,
                                     attachments=email_message.attachments)
            else:
                msg = mail.send_mail(sender=email_message.from_email,
                                     to=email_message.recipients(),
                                     subject=email_message.subject,
                                     body=email_message.body)
        except:
            if not self.fail_silently:
                raise
            return False
        return True